/** 
 *  Copyright 2010 Matthew Werny & Burk Price.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package net.iceflow.db.migration.maven;

import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Collections2;

import net.iceflow.db.migration.MigrationManager;

import org.apache.maven.plugin.MojoExecutionException;

import java.util.Collection;
import java.util.Set;
import net.iceflow.db.migration.MigrationExecuter;

import static java.lang.String.format;

/**
 * Check current schema against available migrations to see if database is up to date,
 * causing the build to fail if the database is not up to date.
 * <p/>
 *
 * @goal check
 */
public class CheckMojo extends AbstractMigrationMojo {

	public void executeMojo() throws MojoExecutionException {
		getLog().info("Checking " + getUrl() + " using migrations at " + getMigrationsPath() + ".");

		Set<MigrationExecuter> pendingMigrations;
		try {
			MigrationManager manager = createMigrationManager();
			pendingMigrations = manager.pendingMigrations();
		} catch (Exception e) {
			throw new MojoExecutionException("Failed to check " + getUrl(), e);
		}

		if (pendingMigrations.isEmpty()) {
			//getLog().info("Database is up-to-date.");
			return;
		}

		Collection<String> pendingMigrationsNames = Collections2.transform(pendingMigrations, new Function<MigrationExecuter, String>() {

			public String apply(MigrationExecuter migration) {
				return migration.getFilename();
			}
		});

		String msg = format("There %s %d pending migrations: \n\n    %s\n\n    Run db-migration:migrate to apply pending migrations.",
			pendingMigrations.size() == 1 ? "is" : "are",
			pendingMigrations.size(),
			Joiner.on("\n    ").join(pendingMigrationsNames));
		getLog().warn(msg);

		throw new MojoExecutionException(format("There %s %d pending migrations, migrate your db and try again.", pendingMigrations.size() == 1 ? "is" : "are", pendingMigrations.size()));
	}
}
